DDOS / app.py
Lahari2005's picture
Create app.py
82ec3bc verified
Raw
History Blame Contribute Delete
11.1 kB
import gradio as gr
import datetime
# ============================================================================
# DETECTION FUNCTION
# ============================================================================
def detect_ddos(flow_duration, total_packets):
"""
Detect DDoS based on Packets Per Second (PPS)
"""
# Convert microseconds to seconds
duration_seconds = flow_duration / 1_000_000
# Calculate PPS
if duration_seconds > 0:
pps = total_packets / duration_seconds
else:
pps = 0
# Determine status based on PPS
if pps < 500:
status = "βœ… NORMAL"
severity = "Low"
color = "#00ff88"
risk = "No threat detected"
attack_type = "Normal Traffic"
emoji = "🟒"
recommendation = "Continue monitoring"
elif pps < 2000:
status = "⚠️ SUSPICIOUS"
severity = "Medium"
color = "#f9ca24"
risk = "Monitor traffic closely"
attack_type = "Suspicious Activity"
emoji = "🟑"
recommendation = "Enable IDS/IPS monitoring"
elif pps < 10000:
status = "🚨 HIGH TRAFFIC"
severity = "High"
color = "#f0932b"
risk = "Possible DDoS attack"
attack_type = "Potential DDoS"
emoji = "🟠"
recommendation = "Apply rate limiting, check firewall"
else:
status = "πŸ”₯ DDoS ATTACK!"
severity = "Critical"
color = "#eb4d4b"
risk = "Immediate action required"
attack_type = "DDoS Attack"
emoji = "πŸ”΄"
recommendation = "Block IPs, enable SYN cookies, contact SOC"
result = {
'status': status,
'severity': severity,
'color': color,
'risk': risk,
'attack_type': attack_type,
'emoji': emoji,
'recommendation': recommendation,
'pps': pps,
'total_packets': int(total_packets),
'duration_us': flow_duration,
'duration_ms': flow_duration / 1000,
'duration_sec': duration_seconds,
'is_attack': pps > 1000,
'timestamp': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
return result
# ============================================================================
# PREDICTION FUNCTION
# ============================================================================
def predict(flow_duration, total_packets):
"""
Gradio prediction function
"""
# Validate inputs
if flow_duration <= 0 or total_packets <= 0:
return """
<div style="background: rgba(255,0,0,0.1); padding: 20px; border-radius: 10px; border: 1px solid #eb4d4b; text-align: center;">
<h3 style="color: #eb4d4b;">❌ Please enter positive values for both fields!</h3>
</div>
"""
# Get detection result
result = detect_ddos(flow_duration, total_packets)
# Format output with HTML
color = result['color']
pps_display = f"{int(result['pps']):,}"
output = f"""
<div style="background: #0a0e17; padding: 25px; border-radius: 15px; border: 2px solid {color};">
<h2 style="color: {color}; text-align: center; font-size: 2em; margin-bottom: 20px;">
{result['emoji']} {result['status']}
</h2>
<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin: 20px 0;">
<div style="background: rgba(255,255,255,0.05); padding: 15px; border-radius: 10px; text-align: center;">
<div style="font-size: 2em; font-weight: bold; color: {color}; font-family: monospace;">
{pps_display}
</div>
<div style="color: #8a8fa8; font-size: 0.9em;">Packets Per Second (PPS)</div>
</div>
<div style="background: rgba(255,255,255,0.05); padding: 15px; border-radius: 10px; text-align: center;">
<div style="font-size: 2em; font-weight: bold; color: #00d4ff; font-family: monospace;">
{result['total_packets']:,}
</div>
<div style="color: #8a8fa8; font-size: 0.9em;">Total Packets</div>
</div>
<div style="background: rgba(255,255,255,0.05); padding: 15px; border-radius: 10px; text-align: center;">
<div style="font-size: 2em; font-weight: bold; color: #7b2ffc; font-family: monospace;">
{result['duration_ms']:.1f} ms
</div>
<div style="color: #8a8fa8; font-size: 0.9em;">Flow Duration</div>
</div>
</div>
<div style="display: flex; justify-content: center; gap: 10px; flex-wrap: wrap; margin: 15px 0;">
<span style="background: {color}20; color: {color}; padding: 6px 18px; border-radius: 20px; border: 1px solid {color}; font-weight: 600;">
{result['attack_type']}
</span>
<span style="background: rgba(255,255,255,0.05); color: #f9ca24; padding: 6px 18px; border-radius: 20px; border: 1px solid rgba(249,202,36,0.2); font-weight: 600;">
{result['severity']} Severity
</span>
<span style="background: rgba(255,255,255,0.05); color: #8a8fa8; padding: 6px 18px; border-radius: 20px; border: 1px solid rgba(255,255,255,0.1);">
{result['risk']}
</span>
</div>
<div style="background: rgba(0,212,255,0.05); padding: 15px; border-radius: 10px; border: 1px solid rgba(0,212,255,0.1); margin: 15px 0;">
<div style="color: #00d4ff; font-weight: 600; margin-bottom: 5px;">πŸ’‘ Recommendation:</div>
<div style="color: #e0e0e0;">{result['recommendation']}</div>
</div>
<div style="text-align: center; color: #4a4f6a; font-size: 0.85em; margin-top: 15px; border-top: 1px solid rgba(255,255,255,0.05); padding-top: 15px;">
Detected at {result['timestamp']}
</div>
</div>
"""
return output
# ============================================================================
# CUSTOM CSS
# ============================================================================
custom_css = """
.gradio-container {
background: linear-gradient(135deg, #0a0e17 0%, #0d1a2b 50%, #0a0e17 100%) !important;
}
.gr-box {
border: 1px solid rgba(0, 212, 255, 0.1) !important;
border-radius: 12px !important;
background: rgba(255, 255, 255, 0.02) !important;
}
input[type="number"] {
background: rgba(255, 255, 255, 0.05) !important;
border: 1px solid rgba(255, 255, 255, 0.1) !important;
color: #e0e0e0 !important;
}
input[type="number"]:focus {
border-color: #00d4ff !important;
box-shadow: 0 0 20px rgba(0, 212, 255, 0.1) !important;
}
label {
color: #8a8fa8 !important;
font-weight: 600 !important;
}
button {
font-weight: 600 !important;
}
"""
# ============================================================================
# CREATE GRADIO INTERFACE
# ============================================================================
def create_interface():
with gr.Blocks(
title="DDoS Detection System",
theme=gr.themes.Soft(
primary_hue="blue",
secondary_hue="purple",
neutral_hue="slate",
),
css=custom_css
) as demo:
gr.Markdown("""
# πŸ›‘οΈ DDoS Detection System
### Detect DDoS attacks using Packets Per Second (PPS) calculation
Enter the **Flow Duration** and **Total Packets** to instantly calculate PPS and detect attacks.
""")
with gr.Row():
with gr.Column(scale=1):
flow_duration = gr.Number(
label="⏱️ Flow Duration (microseconds)",
value=98,
minimum=1,
step=1,
info="Time duration of the network flow in microseconds (Β΅s)"
)
total_packets = gr.Number(
label="πŸ“¦ Total Packets",
value=15,
minimum=1,
step=1,
info="Total number of packets in this flow (Fwd + Bwd)"
)
with gr.Row():
detect_btn = gr.Button("πŸš€ Detect Attack", variant="primary", size="lg")
clear_btn = gr.Button("πŸ”„ Reset", variant="secondary", size="lg")
gr.Markdown("""
---
### πŸ“Š PPS Thresholds
| PPS Range | Status |
|-----------|--------|
| < 500 | βœ… NORMAL |
| 500 - 2,000 | ⚠️ SUSPICIOUS |
| 2,000 - 10,000 | 🚨 HIGH TRAFFIC |
| > 10,000 | πŸ”₯ DDoS ATTACK! |
---
### πŸ’‘ Example Values
- **Normal:** 1,000,000Β΅s, 100 packets β†’ 100 PPS β†’ βœ… NORMAL
- **Suspicious:** 100,000Β΅s, 100 packets β†’ 1,000 PPS β†’ ⚠️ SUSPICIOUS
- **Attack:** 98Β΅s, 15 packets β†’ 153,061 PPS β†’ πŸ”₯ DDoS ATTACK!
""")
with gr.Column(scale=2):
output = gr.HTML(
value="""
<div style="background: rgba(255,255,255,0.03); padding: 60px 40px; border-radius: 15px; text-align: center; border: 1px dashed rgba(255,255,255,0.1);">
<div style="font-size: 4em; margin-bottom: 15px;">πŸ”</div>
<div style="color: #8a8fa8; font-size: 1.2em;">Enter values and click <strong>"Detect Attack"</strong></div>
<div style="color: #4a4f6a; margin-top: 10px;">Results will appear here</div>
</div>
""",
label="Detection Result"
)
# Event handlers
detect_btn.click(
fn=predict,
inputs=[flow_duration, total_packets],
outputs=output
)
clear_btn.click(
fn=lambda: (
98,
15,
'<div style="background: rgba(255,255,255,0.03); padding: 60px 40px; border-radius: 15px; text-align: center; border: 1px dashed rgba(255,255,255,0.1);"><div style="font-size: 4em; margin-bottom: 15px;">πŸ”</div><div style="color: #8a8fa8; font-size: 1.2em;">Enter values and click <strong>"Detect Attack"</strong></div><div style="color: #4a4f6a; margin-top: 10px;">Results will appear here</div></div>'
),
inputs=[],
outputs=[flow_duration, total_packets, output]
)
flow_duration.submit(fn=predict, inputs=[flow_duration, total_packets], outputs=output)
total_packets.submit(fn=predict, inputs=[flow_duration, total_packets], outputs=output)
return demo
# ============================================================================
# LAUNCH
# ============================================================================
demo = create_interface()
# Hugging Face Spaces requires demo.launch() with no arguments
demo.launch()