ids.alfacom.it/deployment/CLEANUP_DETECTIONS_GUIDE.md
marco370 791b7caa4d Add automatic cleanup for old detections and IP blocks
Implement automated detection cleanup after 48 hours and IP unblocking after 2 hours using systemd timers and Python scripts.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 7a657272-55ba-4a79-9a2e-f1ed9bc7a528
Replit-Commit-Checkpoint-Type: intermediate_checkpoint
Replit-Commit-Event-Id: 3809a8a0-8dd5-4b5a-9e32-9e075dab335e
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/449cf7c4-c97a-45ae-8234-e5c5b8d6a84f/7a657272-55ba-4a79-9a2e-f1ed9bc7a528/L6QSDnx
2025-11-25 10:40:44 +00:00

327 lines
8.0 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# IDS - Guida Cleanup Detections Automatico
## 📋 Overview
Sistema automatico di pulizia delle detections e gestione IP bloccati secondo regole temporali:
1. **Cleanup Detections**: Elimina detections non bloccate più vecchie di **48 ore**
2. **Auto-Unblock**: Sblocca IP bloccati da più di **2 ore** senza nuove anomalie
## ⚙️ Componenti
### 1. Script Python: `python_ml/cleanup_detections.py`
Script principale che esegue le operazioni di cleanup:
- Elimina detections vecchie dal database
- Marca come "sbloccati" gli IP nel DB (NON rimuove da MikroTik firewall!)
- Logging completo in `/var/log/ids/cleanup.log`
### 2. Wrapper Bash: `deployment/run_cleanup.sh`
Wrapper che carica le variabili d'ambiente e esegue lo script Python.
### 3. Systemd Service: `ids-cleanup.service`
Service oneshot che esegue il cleanup una volta.
### 4. Systemd Timer: `ids-cleanup.timer`
Timer che esegue il cleanup **ogni ora alle XX:10** (es. 10:10, 11:10, 12:10...).
## 🚀 Installazione
```bash
cd /opt/ids
# Esegui setup automatico
sudo ./deployment/setup_cleanup_timer.sh
# Output:
# ✅ Cleanup timer installato e avviato con successo!
```
## 📊 Monitoraggio
### Stato Timer
```bash
# Verifica che il timer sia attivo
sudo systemctl status ids-cleanup.timer
# Prossima esecuzione programmata
systemctl list-timers ids-cleanup.timer
```
### Log
```bash
# Real-time log
tail -f /var/log/ids/cleanup.log
# Ultime 50 righe
tail -50 /var/log/ids/cleanup.log
# Log completo
cat /var/log/ids/cleanup.log
```
## 🔧 Uso Manuale
### Esecuzione Immediata
```bash
# Via systemd (consigliato)
sudo systemctl start ids-cleanup.service
# Oppure direttamente
sudo ./deployment/run_cleanup.sh
```
### Test con Output Verbose
```bash
cd /opt/ids
source .env
python3 python_ml/cleanup_detections.py
```
## 📝 Regole di Cleanup
### Regola 1: Cleanup Detections (48 ore)
**Query SQL**:
```sql
DELETE FROM detections
WHERE detected_at < NOW() - INTERVAL '48 hours'
AND blocked = false
```
**Logica**:
- Se un IP è stato rilevato ma **non bloccato**
- E non ci sono nuove detections da **48 ore**
- → Eliminalo dal database
**Esempio**:
- IP `1.2.3.4` rilevato il 23/11 alle 10:00
- Non bloccato (risk_score < 80)
- Nessuna nuova detection per 48 ore
- **25/11 alle 10:10** IP eliminato
### Regola 2: Auto-Unblock (2 ore)
**Query SQL**:
```sql
UPDATE detections
SET blocked = false, blocked_at = NULL
WHERE blocked = true
AND blocked_at < NOW() - INTERVAL '2 hours'
AND NOT EXISTS (
SELECT 1 FROM detections d2
WHERE d2.source_ip = detections.source_ip
AND d2.detected_at > NOW() - INTERVAL '2 hours'
)
```
**Logica**:
- Se un IP è **bloccato**
- E bloccato da **più di 2 ore**
- E **nessuna nuova detection** nelle ultime 2 ore
- Sbloccalo nel DB
** ATTENZIONE**: Questo sblocca solo nel **database**, NON rimuove l'IP dalle **firewall list MikroTik**!
**Esempio**:
- IP `5.6.7.8` bloccato il 25/11 alle 08:00
- Nessuna nuova detection per 2 ore
- **25/11 alle 10:10** `blocked=false` nel DB
- **ANCORA nella firewall MikroTik**
### Come rimuovere da MikroTik
```bash
# Via API ML Backend
curl -X POST http://localhost:8000/unblock-ip \
-H "Content-Type: application/json" \
-d '{"ip_address": "5.6.7.8"}'
```
## 🛠️ Configurazione
### Modifica Intervalli
#### Cambia soglia cleanup (es. 72 ore invece di 48)
Modifica `python_ml/cleanup_detections.py`:
```python
# Linea ~47
deleted_count = cleanup_old_detections(conn, hours=72) # ← Cambia qui
```
#### Cambia soglia unblock (es. 4 ore invece di 2)
Modifica `python_ml/cleanup_detections.py`:
```python
# Linea ~51
unblocked_count = unblock_old_ips(conn, hours=4) # ← Cambia qui
```
### Modifica Frequenza Esecuzione
Modifica `deployment/systemd/ids-cleanup.timer`:
```ini
[Timer]
# Ogni 6 ore invece di ogni ora
OnCalendar=00/6:10:00
```
Dopo le modifiche:
```bash
sudo systemctl daemon-reload
sudo systemctl restart ids-cleanup.timer
```
## 📊 Output Esempio
```
============================================================
CLEANUP DETECTIONS - Avvio
============================================================
✅ Connesso al database
[1/2] Cleanup detections vecchie...
Trovate 45 detections da eliminare (più vecchie di 48h)
✅ Eliminate 45 detections vecchie
[2/2] Sblocco IP vecchi...
Trovati 3 IP da sbloccare (bloccati da più di 2h)
- 1.2.3.4 (tipo: ddos, score: 85.2)
- 5.6.7.8 (tipo: port_scan, score: 82.1)
- 9.10.11.12 (tipo: brute_force, score: 90.5)
✅ Sbloccati 3 IP nel database
⚠️ ATTENZIONE: IP ancora presenti nelle firewall list MikroTik!
💡 Per rimuoverli dai router, usa: curl -X POST http://localhost:8000/unblock-ip -d '{"ip_address": "X.X.X.X"}'
============================================================
CLEANUP COMPLETATO
- Detections eliminate: 45
- IP sbloccati (DB): 3
============================================================
```
## 🔍 Troubleshooting
### Timer non parte
```bash
# Verifica che il timer sia enabled
sudo systemctl is-enabled ids-cleanup.timer
# Se disabled, abilita
sudo systemctl enable ids-cleanup.timer
sudo systemctl start ids-cleanup.timer
```
### Errori nel log
```bash
# Controlla errori
grep ERROR /var/log/ids/cleanup.log
# Controlla connessione DB
grep "Connesso al database" /var/log/ids/cleanup.log
```
### Test connessione DB
```bash
cd /opt/ids
source .env
python3 -c "
import psycopg2
conn = psycopg2.connect(
host='$PGHOST',
port=$PGPORT,
user='$PGUSER',
password='$PGPASSWORD',
database='$PGDATABASE'
)
print('✅ DB connesso!')
conn.close()
"
```
## 📈 Metriche
### Query per statistiche
```sql
-- Detections per età
SELECT
CASE
WHEN detected_at > NOW() - INTERVAL '2 hours' THEN '< 2h'
WHEN detected_at > NOW() - INTERVAL '24 hours' THEN '< 24h'
WHEN detected_at > NOW() - INTERVAL '48 hours' THEN '< 48h'
ELSE '> 48h'
END as age_group,
COUNT(*) as count,
COUNT(CASE WHEN blocked THEN 1 END) as blocked_count
FROM detections
GROUP BY age_group
ORDER BY age_group;
-- IP bloccati per durata
SELECT
source_ip,
blocked_at,
EXTRACT(EPOCH FROM (NOW() - blocked_at)) / 3600 as hours_blocked,
anomaly_type,
risk_score::numeric
FROM detections
WHERE blocked = true
ORDER BY blocked_at DESC;
```
## ⚙️ Integrazione con Altri Sistemi
### Notifiche Email (opzionale)
Aggiungi a `python_ml/cleanup_detections.py`:
```python
import smtplib
from email.mime.text import MIMEText
if unblocked_count > 0:
msg = MIMEText(f"Sbloccati {unblocked_count} IP")
msg['Subject'] = 'IDS Cleanup Report'
msg['From'] = 'ids@example.com'
msg['To'] = 'admin@example.com'
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
```
### Webhook (opzionale)
```python
import requests
requests.post('https://hooks.slack.com/...', json={
'text': f'IDS Cleanup: {deleted_count} detections eliminate, {unblocked_count} IP sbloccati'
})
```
## 🔒 Sicurezza
- Script eseguito come **root** (necessario per systemd)
- Credenziali DB caricate da `.env` (NON hardcoded)
- Log in `/var/log/ids/` con permessi `644`
- Service con `NoNewPrivileges=true` e `PrivateTmp=true`
## 📅 Scheduler
Il timer è configurato per eseguire:
- **Frequenza**: Ogni ora
- **Minuto**: XX:10 (10 minuti dopo l'ora)
- **Randomizzazione**: ±5 minuti per load balancing
- **Persistent**: Recupera esecuzioni perse durante downtime
**Esempio orari**: 00:10, 01:10, 02:10, ..., 23:10
## ✅ Checklist Post-Installazione
- [ ] Timer installato: `systemctl status ids-cleanup.timer`
- [ ] Prossima esecuzione visibile: `systemctl list-timers`
- [ ] Test manuale OK: `sudo ./deployment/run_cleanup.sh`
- [ ] Log creato: `ls -la /var/log/ids/cleanup.log`
- [ ] Nessun errore nel log: `grep ERROR /var/log/ids/cleanup.log`
- [ ] Cleanup funzionante: verificare conteggio detections prima/dopo
## 🆘 Supporto
Per problemi o domande:
1. Controlla log: `tail -f /var/log/ids/cleanup.log`
2. Verifica timer: `systemctl status ids-cleanup.timer`
3. Test manuale: `sudo ./deployment/run_cleanup.sh`
4. Apri issue su GitHub o contatta il team