Implement a systemd timer and Python script to periodically detect and automatically block malicious IP addresses based on risk scores, improving the application's security posture. Replit-Commit-Author: Agent Replit-Commit-Session-Id: 7a657272-55ba-4a79-9a2e-f1ed9bc7a528 Replit-Commit-Checkpoint-Type: full_checkpoint Replit-Commit-Event-Id: 05ab2f73-e195-4de9-a183-cd4729713b92 Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/449cf7c4-c97a-45ae-8234-e5c5b8d6a84f/7a657272-55ba-4a79-9a2e-f1ed9bc7a528/31VdIyL
64 lines
2.2 KiB
Python
64 lines
2.2 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
IDS Auto-Blocking Script
|
|
Rileva e blocca automaticamente IP con risk_score >= 80
|
|
Eseguito periodicamente da systemd timer (ogni 5 minuti)
|
|
"""
|
|
import requests
|
|
import sys
|
|
from datetime import datetime
|
|
|
|
ML_API_URL = "http://localhost:8000"
|
|
|
|
def auto_block():
|
|
"""Esegue detection e blocking automatico degli IP critici"""
|
|
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
print(f"[{timestamp}] 🔍 Starting auto-block detection...")
|
|
|
|
try:
|
|
# Chiama endpoint ML /detect con auto_block=true
|
|
response = requests.post(
|
|
f"{ML_API_URL}/detect",
|
|
json={
|
|
"max_records": 5000, # Analizza ultimi 5000 log
|
|
"hours_back": 1.0, # Ultima ora
|
|
"risk_threshold": 80.0, # Solo IP critici (score >= 80)
|
|
"auto_block": True # BLOCCA AUTOMATICAMENTE
|
|
},
|
|
timeout=120 # 2 minuti timeout
|
|
)
|
|
|
|
if response.status_code == 200:
|
|
data = response.json()
|
|
detections = len(data.get("detections", []))
|
|
blocked = data.get("blocked", 0)
|
|
|
|
if blocked > 0:
|
|
print(f"✓ Detection completata: {detections} anomalie rilevate, {blocked} IP bloccati")
|
|
else:
|
|
print(f"✓ Detection completata: {detections} anomalie rilevate, nessun nuovo IP da bloccare")
|
|
|
|
return 0
|
|
else:
|
|
print(f"✗ API error: HTTP {response.status_code}")
|
|
print(f" Response: {response.text}")
|
|
return 1
|
|
|
|
except requests.exceptions.ConnectionError:
|
|
print("✗ ERRORE: ML Backend non raggiungibile su http://localhost:8000")
|
|
print(" Verifica che ids-ml-backend.service sia attivo:")
|
|
print(" sudo systemctl status ids-ml-backend")
|
|
return 1
|
|
except requests.exceptions.Timeout:
|
|
print("✗ ERRORE: Timeout dopo 120 secondi. Detection troppo lenta?")
|
|
return 1
|
|
except Exception as e:
|
|
print(f"✗ ERRORE imprevisto: {type(e).__name__}: {e}")
|
|
import traceback
|
|
traceback.print_exc()
|
|
return 1
|
|
|
|
if __name__ == "__main__":
|
|
exit_code = auto_block()
|
|
sys.exit(exit_code)
|