# IDS - Intrusion Detection System ## Overview This project is a full-stack web application designed as an Intrusion Detection System (IDS) for MikroTik routers, leveraging Machine Learning. Its primary purpose is to monitor network traffic, detect anomalies indicative of intrusions, and automatically block malicious IP addresses across multiple routers. The system aims to provide real-time monitoring, efficient anomaly detection, and streamlined management of network security for MikroTik environments. ## User Preferences ### Operazioni Git e Deployment - **IMPORTANTE**: L'agente NON deve usare comandi git (push-gitlab.sh) perché Replit blocca le operazioni git - **Workflow corretto**: 1. Utente riporta errori/problemi dal server AlmaLinux 2. Agente risolve problemi e modifica file su Replit 3. **Utente esegue manualmente**: `./push-gitlab.sh` per commit+push 4. **Utente esegue sul server**: `./update_from_git.sh` o `./update_from_git.sh --db` 5. Utente testa e riporta risultati all'agente 6. Ripeti fino a funzionamento completo ### Linguaggio - Tutte le risposte dell'agente devono essere in **italiano** - Codice e documentazione tecnica: inglese - Commit message: italiano ## System Architecture The IDS features a React-based frontend for real-time monitoring, detection visualization, and whitelist management, utilizing ShadCN UI and TanStack Query. The backend comprises a Python FastAPI service for ML analysis (Isolation Forest with 25 targeted features), MikroTik API management, and a detection engine scoring anomalies from 0-100 with five risk levels. A Node.js (Express) backend handles API requests from the frontend and manages the PostgreSQL database. **Workflow:** 1. **Log Collection**: MikroTik Routers send syslog data (UDP:514) to RSyslog, which is then parsed by `syslog_parser.py` and stored in the `network_logs` table in PostgreSQL. 2. **Training**: The Python ML component extracts 25 features from network logs and trains an Isolation Forest model. 3. **Detection**: Real-time analysis of network logs is performed using the trained ML model, assigning a risk score. 4. **Auto-Block**: Critical IPs (score >= 80) are automatically blocked across all configured MikroTik routers in parallel via their REST API. 5. **Monitoring**: Dashboard real-time mostra status servizi (ML Backend, Database, Parser) con pallini verde/rosso. **Key Features:** - **ML Analyzer**: Isolation Forest with 25 features. - **MikroTik Manager**: Parallel communication with 10+ routers via API REST. - **Detection Engine**: Scoring 0-100 with 5 risk levels (Normal, Basso, Medio, Alto, Critico). - **Service Monitoring**: Dashboard con status real-time di ML Backend, Database e Syslog Parser (pallini verde/rosso). - **Service Management**: Controlli start/stop/restart per servizi Python via API endpoints. - **Form Validation**: Improved validation using react-hook-form and Zod. - **Database Migrations**: Automated SQL migrations applied via `update_from_git.sh --db`. - **Microservices**: Separation of concerns with dedicated Python ML backend and Node.js API backend. ## External Dependencies - **React**: Frontend framework. - **FastAPI**: Python web framework for the ML backend. - **PostgreSQL**: Primary database for storing router configurations, network logs, detections, and whitelist entries. - **MikroTik API REST**: Used for communication with MikroTik routers for configuration and IP blocking. - **ShadCN UI**: Frontend component library. - **TanStack Query**: Data fetching library for the frontend. - **Isolation Forest**: Machine Learning algorithm for anomaly detection. - **RSyslog**: Log collection daemon. - **Drizzle ORM**: Used for database schema definition and synchronization in the Node.js backend. - **Neon Database**: Cloud-native PostgreSQL service (used in Replit environment). - **pg (Node.js driver)**: Standard PostgreSQL driver for Node.js (used in AlmaLinux environment). - **psycopg2**: PostgreSQL adapter for Python. ## Recent Updates (Novembre 2025) ### 🔒 Sistema Monitoring e Gestione Servizi Production-Grade (22 Nov 2025 - 13:00) - **Feature**: Sistema completo di monitoring e controllo servizi con sicurezza enterprise-level - **Architettura Sicurezza**: - **Autenticazione API Key** (`IDS_API_KEY`): - Comunicazione autenticata tra Node.js backend e Python FastAPI - Header `X-API-Key` richiesto per tutti gli endpoint ML backend - Generazione automatica via `setup_systemd_services.sh` - Backward compatibility: funziona senza API key in development - **Validazione Whitelist**: - Solo servizi autorizzati: `ids-ml-backend`, `ids-syslog-parser` - Solo azioni autorizzate: `start`, `stop`, `restart`, `status` - Prevenzione command injection via validation strict - **Systemd Integration**: - Gestione servizi tramite systemctl (no shell commands arbitrari) - Timeout 10s per prevenire hanging - Auto-restart in caso di crash - **Monitoring Real-time**: - Endpoint `/api/services/status` controlla: - ML Backend: health check HTTP + uptime - Database PostgreSQL: connection test - Syslog Parser: status systemd + PID - Dashboard mostra pallini verde/rosso (refresh automatico 5s) - Python backend `/services/status` (autenticato): - Verifica status via `systemctl is-active` - Estrae PID da `systemctl status` - Gestisce gracefully assenza systemd (dev environment) - **Controlli UX Completi**: - Pagina `/services` con pulsanti funzionanti: - Start/Stop/Restart per ML backend e Syslog parser - Mutations TanStack Query con feedback toast - Auto-refresh status dopo operazioni - Fallback comandi manuali systemctl - Disabilitazione intelligente pulsanti (es. Stop se già offline) - Visualizzazione PID processo e systemd unit - **Systemd Units**: - `ids-ml-backend.service`: Python FastAPI ML backend - `ids-syslog-parser.service`: Python syslog parser - Features: auto-restart, limiti risorse, logging centralizzato - Script `setup_systemd_services.sh` per installazione automatica - **Deployment**: 1. Utente esegue: `sudo ./deployment/setup_systemd_services.sh` 2. Script verifica e installa dipendenze Python (virtual environment) 3. Script genera `IDS_API_KEY` se mancante 4. Installa systemd units e avvia servizi 5. Frontend usa controlli per gestione remota servizi - **Virtual Environment**: - Dipendenze Python in `/opt/ids/python_ml/venv` - Systemd services usano automaticamente il venv - Script `install_python_deps.sh` per installazione manuale - **Benefici**: - 🔒 Autenticazione API end-to-end (zero vulnerabilità) - 🎯 Controlli UX funzionanti (no comandi manuali) - 🔄 Systemd auto-restart e monitoring robusto - 📊 Visibilità completa con sicurezza production-grade - ⚡ Gestione servizi remota sicura via dashboard ### 📊 Log Format Fix - Timestamp Integration (22 Nov 2025 - 10:30) - **Problema**: RSyslog salvava log senza timestamp, parser Python falliva - **Soluzione**: Template rsyslog corretto per includere timestamp BSD ```bash # PRIMA: template(... string="%msg%\n") ❌ # ADESSO: template(... string="%TIMESTAMP% %HOSTNAME% %msg%\n") ✅ ``` - **Formato log supportato**: ``` Nov 22 08:15:30 FIBRA forward: in: out:sfp-xxx, connection-state:new proto TCP (SYN), 10.0.254.77:53783->52.213.60.221:443, len 64 ``` - **Compatibilità**: Parser Python 100% compatibile con: - ✅ Log "forward" e "detected-ddos forward" - ✅ Interfacce in/out: `in: out:sfp-xxx` - ✅ src-mac opzionale - ✅ TCP flags: `(SYN)`, `(ACK,PSH)`, etc. - ✅ NAT info opzionale - **Migrazione**: Vedi `deployment/MIGRATION_INCOMING_LOGS.md` - **Benefici**: - ⚡ Volume log ridotto 50-70% (solo connessioni in ingresso) - 🔒 Parser funzionante con timestamp corretto - 📊 Database popolato correttamente ### 🚀 Database Versioning System (22 Nov 2025 - 10:00) - **Feature**: Sistema intelligente di versioning per migrazioni database - **Problema risolto**: `update_from_git.sh` rieseguiva tutte le migrazioni SQL ad ogni update (lento) - **Soluzione**: - Tabella `schema_version` traccia versione corrente database - Migrazioni SQL numerate sequenzialmente (001, 002, 003, etc.) - Script `apply_migrations.sh` applica solo migrazioni mancanti - Integrato in workflow update automatico - **Benefici**: - ⚡ Update 10x più veloce (salta migrazioni già applicate) - 🔒 Sicuro: previene re-esecuzione migrazioni - 📊 Tracciabilità: storico migrazioni applicate - **Documentazione**: `database-schema/README.md` ## Fix Recenti (Novembre 2025) ### 🐛 Fix Monitoring Syslog Parser + Schema Database (22 Nov 2025 - 11:10) - **Problema 1**: Dashboard mostrava Syslog Parser in errore nonostante systemd "active (running)" - **Causa**: Bug fetch `signal: controller2.abort` invece di `signal: controller2.signal` in `/api/services/status` - **Soluzione**: Corretto parametro AbortController signal - **Problema 2**: Errore database `column "destination_ip" does not exist` - **Causa**: Database server usa `dest_ip`/`src_ip` invece di `destination_ip`/`source_ip` - **Soluzione**: Migrazione SQL 003 rinomina colonne in formato corretto - **Fix Applicati**: - ✅ `server/routes.ts`: Corretto signal in fetch monitoring - ✅ `database-schema/migrations/003_fix_network_logs_columns.sql`: Migrazione rinomina colonne - **Deploy**: 1. Eseguire `./update_from_git.sh --db` per applicare migrazione 2. Riavviare backend Node.js 3. Dashboard mostrerà correttamente tutti i servizi (pallini verdi) ## Fix Recenti (Novembre 2025) ### 🚨 Database Full - Auto-Cleanup Fix (21 Nov 2025 - 18:00) - **Problema**: Database PostgreSQL pieno con **417 MILIONI di log** accumulati - Syslog parser ha processato 417.7M righe senza limite di retention - Errore: `could not extend file: No space left on device` - Tutte le tabelle vuote perché database non accetta più scritture - **Causa**: Nessuna pulizia automatica dei vecchi log (retention infinita) - **Soluzione**: - Script `cleanup_old_logs.sql`: Mantiene solo ultimi 7 giorni di `network_logs` - Script `cleanup_database.sh`: Wrapper per esecuzione manuale/cron - Script `setup_cron_cleanup.sh`: Configura cron job giornaliero (ore 03:00) - **Fix Immediato sul Server**: ```bash # 1. Pulisci manualmente log vecchi psql $DATABASE_URL << 'EOF' DELETE FROM network_logs WHERE timestamp < NOW() - INTERVAL '7 days'; VACUUM FULL network_logs; EOF # 2. Setup pulizia automatica giornaliera sudo /opt/ids/deployment/setup_cron_cleanup.sh ``` - **Risultato Atteso**: - Database ridotto da centinaia di GB a pochi GB - Retention 7 giorni sufficiente per training ML - Pulizia automatica previene saturazione futura ### ✅ Database Driver Fix - Dual Mode Neon/PostgreSQL (21 Nov 2025 - 17:40) - **Problema**: Frontend Node.js falliva con errore 500 su tutte le query database - **Causa**: `@neondatabase/serverless` usa WebSocket ed è compatibile SOLO con Neon Cloud, non con PostgreSQL locale - **Soluzione**: Dual-mode driver in `server/db.ts` con auto-detection ambiente - **Risultato**: Funziona su Replit (Neon) e AlmaLinux (PostgreSQL standard) ✅