From f356181ada38788f1f3a23a0fc5684a0969d3d5a Mon Sep 17 00:00:00 2001 From: marco370 <48531002-marco370@users.noreply.replit.com> Date: Mon, 17 Nov 2025 15:19:13 +0000 Subject: [PATCH] Add comprehensive installation and configuration guides for the IDS system Create detailed Markdown documentation for IDS installation, including quick start, step-by-step, and configuration details. Replit-Commit-Author: Agent Replit-Commit-Session-Id: 7a657272-55ba-4a79-9a2e-f1ed9bc7a528 Replit-Commit-Checkpoint-Type: full_checkpoint Replit-Commit-Event-Id: e8ff5164-9660-4159-93ac-0d6cae981bb0 Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/449cf7c4-c97a-45ae-8234-e5c5b8d6a84f/7a657272-55ba-4a79-9a2e-f1ed9bc7a528/c9ITWqD --- .gitignore | 48 +- .replit | 4 + GUIDA_INSTALLAZIONE.md | 284 ++++++++++ deployment/COMANDI_RAPIDI.md | 375 +++++++++++++ deployment/INSTALLAZIONE_STEP_BY_STEP.md | 643 +++++++++++++++++++++++ git.env.example | 26 + 6 files changed, 1379 insertions(+), 1 deletion(-) create mode 100644 GUIDA_INSTALLAZIONE.md create mode 100644 deployment/COMANDI_RAPIDI.md create mode 100644 deployment/INSTALLAZIONE_STEP_BY_STEP.md create mode 100644 git.env.example diff --git a/.gitignore b/.gitignore index f9ba7f8..948bafc 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,50 @@ dist .DS_Store server/public vite.config.ts.* -*.tar.gz \ No newline at end of file +*.tar.gz + +# Environment variables e secrets (NON committare!) +.env +.env.* +!.env.example +git.env +!git.env.example + +# Backup e log +database-backups/ +backups/ +*.log +*.log.* + +# Python +__pycache__/ +*.py[cod] +*$py.class +*.so +.Python +*.egg-info/ +dist/ +build/ +*.pkl +*.joblib +python_ml/models/*.pkl +python_ml/models/*.joblib + +# Database dumps +*.sql +*.sql.gz +*.dump + +# IDE +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# OS +.DS_Store +Thumbs.db + +# Versioning +version.json.backup \ No newline at end of file diff --git a/.replit b/.replit index af7007c..7f8eba1 100644 --- a/.replit +++ b/.replit @@ -14,6 +14,10 @@ run = ["npm", "run", "start"] localPort = 5000 externalPort = 80 +[[ports]] +localPort = 44261 +externalPort = 3000 + [env] PORT = "5000" diff --git a/GUIDA_INSTALLAZIONE.md b/GUIDA_INSTALLAZIONE.md new file mode 100644 index 0000000..8e7a979 --- /dev/null +++ b/GUIDA_INSTALLAZIONE.md @@ -0,0 +1,284 @@ +# πŸš€ IDS - Guida Rapida Installazione + +Installazione completa sistema IDS su AlmaLinux 9 con aggiornamenti da git.alfacom.it + +--- + +## πŸ“– Documenti Disponibili + +1. **`deployment/INSTALLAZIONE_STEP_BY_STEP.md`** ← **SEGUI QUESTA GUIDA** + - πŸ“‹ Guida completa passo-passo + - βœ… 25 step con comandi esatti + - πŸ” Checklist completa + - πŸ› Troubleshooting + +2. **`deployment/COMANDI_RAPIDI.md`** + - ⚑ Riferimento veloce comandi + - πŸ”„ Operazioni comuni + - πŸ“Š Monitoring e debug + +3. **`deployment/README_DEPLOYMENT.md`** + - πŸ“š Documentazione tecnica completa + - πŸ—οΈ Architettura sistema + - βš™οΈ Configurazione avanzata + +4. **`deployment/CONFIGURAZIONE_ROUTER_MIKROTIK.md`** + - πŸ“‘ Setup router MikroTik + - πŸ”§ Configurazione syslog + - βœ… Verifica connessione + +--- + +## ⚑ Quick Start (3 minuti) + +### 1. Prerequisiti +- βœ… Server AlmaLinux 9 +- βœ… Accesso root SSH +- βœ… Credenziali git.alfacom.it (username + token) + +### 2. Installazione Base + +```bash +# Connetti al server +ssh root@ + +# Clone repository temporaneo +cd /tmp +git clone https://:@git.alfacom.it//ids.git +cd ids + +# Esegui setup +chmod +x deployment/setup_almalinux.sh +./deployment/setup_almalinux.sh +``` + +### 3. Setup Definitivo + +```bash +# Clone in posizione finale +cd /opt/ids +sudo -u ids git clone https://:@git.alfacom.it//ids.git . + +# Configura git.env +sudo -u ids cp git.env.example git.env +sudo -u ids nano git.env # Inserisci credenziali git + +# Configura .env +sudo -u ids cp .env.example .env +sudo -u ids nano .env # Inserisci password (vedi sotto) +``` + +### 4. Genera Password Sicure + +```bash +# Password database +openssl rand -base64 32 + +# Session secret +openssl rand -base64 32 + +# Copia gli output in .env +``` + +### 5. Installa Dipendenze + +```bash +cd /opt/ids +sudo -u ids npm install +cd python_ml && sudo -u ids pip3.11 install -r requirements.txt +cd /opt/ids && sudo -u ids npm run db:push +``` + +### 6. Configura Syslog e Avvia + +```bash +# Syslog per router +./deployment/setup_syslog_server.sh + +# Avvia tutto +./deployment/setup_crontab.sh +``` + +### 7. Verifica + +```bash +# Processi attivi +ps aux | grep -E 'python|node|syslog' + +# API funzionante +curl http://localhost:8000/health +curl http://localhost:5000 + +# Dashboard web +http://:5000 +``` + +--- + +## πŸ”§ File di Configurazione + +### git.env (Credenziali Git) + +```bash +GITLAB_USER=tuo-username +GITLAB_TOKEN=glpat-abc123xyz +GITLAB_REPO=https://git.alfacom.it/owner/ids.git +GITLAB_BRANCH=main +``` + +> **Token**: git.alfacom.it β†’ Settings β†’ Access Tokens +> Permessi: `api`, `read_repository`, `write_repository` + +### .env (Secrets Applicazione) + +```bash +PGHOST=localhost +PGPORT=5432 +PGDATABASE=ids_database +PGUSER=ids_user +PGPASSWORD= +SESSION_SECRET= +VITE_PYTHON_API_URL=http://localhost:8000 +NODE_ENV=production +``` + +> **IMPORTANTE**: `.env` e `git.env` NON vanno su git (sono in `.gitignore`) + +--- + +## πŸ“‘ Configurazione Router MikroTik + +Su **OGNI router**: + +```mikrotik +/system logging action +add name=ids-server target=remote remote= remote-port=514 + +/system logging +add action=ids-server topics=firewall,info + +/ip firewall filter +add chain=forward action=accept log=yes log-prefix="ACCEPT: " +add chain=forward action=drop log=yes log-prefix="DROP: " +``` + +Verifica log sul server: +```bash +tail -f /var/log/mikrotik/raw.log +``` + +--- + +## πŸ”„ Aggiornamenti da Git + +```bash +cd /opt/ids +sudo -u ids ./deployment/update_from_git.sh +``` + +Questo fa: +1. Backup `.env` +2. `git pull` da git.alfacom.it +3. Ripristina `.env` +4. Aggiorna dipendenze +5. Sync database +6. Restart servizi + +--- + +## 🎯 Primo Training ML + +Dopo **24 ore** di raccolta log (almeno 10.000 log): + +```bash +# Verifica log raccolti +psql -U ids_user -d ids_database -c "SELECT COUNT(*) FROM network_logs;" + +# Training +curl -X POST http://localhost:8000/train \ + -H "Content-Type: application/json" \ + -d '{"max_records": 10000, "hours_back": 24}' + +# Detection (giΓ  automatica ogni 5min) +curl -X POST http://localhost:8000/detect \ + -H "Content-Type: application/json" \ + -d '{"max_records": 5000, "auto_block": true, "risk_threshold": 75}' +``` + +--- + +## πŸ“Š Monitoring + +### Log Principali + +```bash +tail -f /var/log/ids/backend.log # Backend Python +tail -f /var/log/ids/frontend.log # Frontend Node +tail -f /var/log/ids/syslog_parser.log # Parser log router +tail -f /var/log/ids/training.log # Training ML +tail -f /var/log/ids/detect.log # Detection +tail -f /var/log/mikrotik/raw.log # Log router in arrivo +``` + +### Comandi Utili + +```bash +# Restart completo +/opt/ids/deployment/restart_all.sh + +# Stato processi +ps aux | grep -E 'python|node|syslog' + +# Database +psql -U ids_user -d ids_database + +# Crontab +crontab -u ids -l +``` + +--- + +## πŸ› Problemi Comuni + +| Problema | Soluzione | +|----------|-----------| +| Log non arrivano | `systemctl restart rsyslog` + verifica firewall | +| Database vuoto | Verifica `syslog_parser.py` attivo | +| Backend non risponde | `/opt/ids/deployment/check_backend.sh` | +| Frontend non carica | `/opt/ids/deployment/check_frontend.sh` | + +--- + +## πŸ“š Documentazione Completa + +- **Installazione**: `deployment/INSTALLAZIONE_STEP_BY_STEP.md` +- **Comandi**: `deployment/COMANDI_RAPIDI.md` +- **Deployment**: `deployment/README_DEPLOYMENT.md` +- **Router**: `deployment/CONFIGURAZIONE_ROUTER_MIKROTIK.md` +- **Risposte FAQ**: `RISPOSTA_DEPLOYMENT.md` + +--- + +## βœ… Checklist Rapida + +- [ ] Server AlmaLinux 9 pronto +- [ ] `setup_almalinux.sh` eseguito +- [ ] `git.env` configurato +- [ ] `.env` configurato con password sicure +- [ ] Dipendenze installate (`npm install`, `pip install`) +- [ ] Database schema sincronizzato (`npm run db:push`) +- [ ] Syslog configurato (`setup_syslog_server.sh`) +- [ ] Router MikroTik configurati +- [ ] Sistema avviato (`setup_crontab.sh`) +- [ ] Processi attivi (python, node, syslog_parser) +- [ ] API funzionanti (curl localhost:8000/health) +- [ ] Dashboard accessibile (http://IP:5000) +- [ ] Log arrivano (`tail -f /var/log/mikrotik/raw.log`) +- [ ] Database si popola (SELECT COUNT(*) FROM network_logs) +- [ ] Training eseguito (dopo 24h) + +--- + +**Sistema pronto! πŸ›‘οΈ** + +Per dettagli: `cat deployment/INSTALLAZIONE_STEP_BY_STEP.md` diff --git a/deployment/COMANDI_RAPIDI.md b/deployment/COMANDI_RAPIDI.md new file mode 100644 index 0000000..959f609 --- /dev/null +++ b/deployment/COMANDI_RAPIDI.md @@ -0,0 +1,375 @@ +# ⚑ Comandi Rapidi IDS + +Riferimento veloce per operazioni comuni sul sistema IDS. + +--- + +## πŸš€ Installazione Iniziale (Solo Prima Volta) + +```bash +# 1. Clone repository +cd /opt/ids +sudo -u ids git clone https://:@git.alfacom.it//ids.git . + +# 2. Setup sistema +./deployment/setup_almalinux.sh + +# 3. Configura environment +sudo -u ids cp .env.example .env +sudo -u ids cp git.env.example git.env +sudo -u ids nano .env # Configura password +sudo -u ids nano git.env # Configura git + +# 4. Installa dipendenze +cd /opt/ids +sudo -u ids npm install +cd python_ml && sudo -u ids pip3.11 install -r requirements.txt + +# 5. Database +cd /opt/ids +sudo -u ids npm run db:push + +# 6. Syslog +./deployment/setup_syslog_server.sh + +# 7. Avvio +./deployment/setup_crontab.sh +``` + +--- + +## πŸ”„ Aggiornamento da Git + +```bash +cd /opt/ids +sudo -u ids ./deployment/update_from_git.sh +``` + +--- + +## πŸ” Monitoring + +### Processi Attivi +```bash +ps aux | grep -E 'python.*main|npm.*dev|syslog_parser' +``` + +### Log Real-time +```bash +# Backend Python +tail -f /var/log/ids/backend.log + +# Frontend Node +tail -f /var/log/ids/frontend.log + +# Syslog Parser +tail -f /var/log/ids/syslog_parser.log + +# Training ML +tail -f /var/log/ids/training.log + +# Detection +tail -f /var/log/ids/detect.log + +# Log router +tail -f /var/log/mikrotik/raw.log +``` + +--- + +## πŸ”„ Restart Servizi + +```bash +# Restart completo +/opt/ids/deployment/restart_all.sh + +# Solo backend Python +/opt/ids/deployment/check_backend.sh + +# Solo frontend +/opt/ids/deployment/check_frontend.sh +``` + +--- + +## πŸ—„οΈ Database + +### Accesso PostgreSQL +```bash +psql -U ids_user -d ids_database +``` + +### Query Utili +```sql +-- Conta log totali +SELECT COUNT(*) FROM network_logs; + +-- Ultimi 10 log +SELECT * FROM network_logs ORDER BY timestamp DESC LIMIT 10; + +-- Detections bloccate +SELECT COUNT(*) FROM detections WHERE blocked = true; + +-- Router configurati +SELECT * FROM routers; + +-- Whitelist IP +SELECT * FROM whitelist; + +-- Training history +SELECT * FROM training_history ORDER BY trained_at DESC LIMIT 5; +``` + +### Backup Manuale +```bash +/opt/ids/deployment/backup_db.sh +``` + +--- + +## πŸ€– Machine Learning + +### Training Manuale +```bash +curl -X POST http://localhost:8000/train \ + -H "Content-Type: application/json" \ + -d '{"max_records": 10000, "hours_back": 24, "contamination": 0.01}' +``` + +### Detection Manuale +```bash +curl -X POST http://localhost:8000/detect \ + -H "Content-Type: application/json" \ + -d '{"max_records": 5000, "auto_block": true, "risk_threshold": 75}' +``` + +### Statistiche +```bash +curl http://localhost:8000/stats | jq +``` + +### Health Check +```bash +curl http://localhost:8000/health +``` + +--- + +## πŸ”₯ Firewall + +### Verifica Regole +```bash +firewall-cmd --list-all +``` + +### Apri Porta +```bash +firewall-cmd --permanent --add-port=514/udp +firewall-cmd --reload +``` + +--- + +## πŸ“‘ Syslog / Router + +### Verifica Rsyslog +```bash +systemctl status rsyslog +``` + +### Restart Rsyslog +```bash +systemctl restart rsyslog +``` + +### Verifica Porta 514 +```bash +netstat -ulnp | grep 514 +``` + +### Test Log da Router +Sul router MikroTik: +```mikrotik +/log print where topics~"firewall" +``` + +--- + +## ⏰ Crontab + +### Visualizza Crontab +```bash +crontab -u ids -l +``` + +### Modifica Crontab +```bash +crontab -u ids -e +``` + +--- + +## πŸ”§ Troubleshooting + +### Log non arrivano +```bash +# Verifica rsyslog +systemctl status rsyslog +netstat -ulnp | grep 514 + +# Verifica log file +ls -la /var/log/mikrotik/ +tail -f /var/log/mikrotik/raw.log + +# Riavvia rsyslog +systemctl restart rsyslog +``` + +### Database non si popola +```bash +# Verifica parser +ps aux | grep syslog_parser +tail -f /var/log/ids/syslog_parser.log + +# Riavvia parser +pkill -f syslog_parser +cd /opt/ids/python_ml +sudo -u ids nohup python3.11 syslog_parser.py > /var/log/ids/syslog_parser.log 2>&1 & +``` + +### Backend non risponde +```bash +# Verifica processo +ps aux | grep "python.*main" +tail -f /var/log/ids/backend.log + +# Test API +curl http://localhost:8000/health + +# Riavvia +/opt/ids/deployment/check_backend.sh +``` + +### Frontend non carica +```bash +# Verifica processo +ps aux | grep "npm.*dev" +tail -f /var/log/ids/frontend.log + +# Test +curl http://localhost:5000 + +# Riavvia +/opt/ids/deployment/check_frontend.sh +``` + +--- + +## πŸ“Š Spazio Disco + +```bash +# Verifica spazio +df -h + +# Dimensione log +du -sh /var/log/ids/* +du -sh /var/log/mikrotik/* + +# Pulisci log vecchi +find /var/log/ids -name "*.log" -size +100M -exec truncate -s 50M {} \; + +# Pulisci backup vecchi +find /opt/ids/backups -name "*.sql.gz" -mtime +7 -delete +``` + +--- + +## 🌐 Accesso Web + +```bash +# Dashboard +http://:5000 + +# API Backend Docs +http://:8000/docs +``` + +--- + +## πŸ” Sicurezza + +### Genera Password Sicura +```bash +openssl rand -base64 32 +``` + +### Cambia Password Database +```bash +# Genera nuova password +NEW_PASS=$(openssl rand -base64 32) +echo "Nuova password: $NEW_PASS" + +# Aggiorna PostgreSQL +sudo -u postgres psql -c "ALTER USER ids_user WITH PASSWORD '$NEW_PASS';" + +# Aggiorna .env +sudo -u ids nano /opt/ids/.env +# Modifica PGPASSWORD= + +# Restart servizi +/opt/ids/deployment/restart_all.sh +``` + +--- + +## πŸ“‹ Info Sistema + +```bash +# Versione sistema +cat /etc/os-release + +# Versioni software +python3.11 --version +node --version +npm --version +psql --version + +# Uptime +uptime + +# Memoria +free -h + +# CPU +top -bn1 | head -20 +``` + +--- + +## 🚨 Comandi Emergenza + +### Stop Tutto +```bash +pkill -f "python.*main" +pkill -f "npm.*dev" +pkill -f "syslog_parser" +``` + +### Restart Completo Sistema +```bash +/opt/ids/deployment/restart_all.sh +``` + +### Restore Backup Database +```bash +# Lista backup disponibili +ls -lh /opt/ids/backups/ + +# Restore backup specifico +gunzip -c /opt/ids/backups/ids_backup_20250115_120000.sql.gz | \ + psql -U ids_user -d ids_database +``` + +--- + +**Per guida completa:** `cat /opt/ids/deployment/INSTALLAZIONE_STEP_BY_STEP.md` diff --git a/deployment/INSTALLAZIONE_STEP_BY_STEP.md b/deployment/INSTALLAZIONE_STEP_BY_STEP.md new file mode 100644 index 0000000..0abcb2a --- /dev/null +++ b/deployment/INSTALLAZIONE_STEP_BY_STEP.md @@ -0,0 +1,643 @@ +# πŸš€ Installazione IDS su AlmaLinux 9 - Guida Passo-Passo + +Questa guida ti accompagna dall'installazione completa del sistema IDS su un server AlmaLinux 9 pulito fino al primo avvio. + +--- + +## πŸ“‹ Prerequisiti + +- **Server AlmaLinux 9** con accesso root SSH +- **Accesso a git.alfacom.it** (username e token) +- **Almeno 4GB RAM** e 20GB disco libero +- **Router MikroTik** configurabili (almeno 1 per testing) + +--- + +## πŸ”§ PARTE 1: Installazione Base Sistema + +### Step 1: Connettiti al Server + +```bash +# Connettiti al server AlmaLinux come root +ssh root@ + +# Esempio: +# ssh root@192.168.1.100 +``` + +### Step 2: Aggiorna Sistema + +```bash +# Aggiorna tutti i pacchetti +dnf update -y + +# Riavvia se necessario (kernel update) +# reboot +``` + +### Step 3: Installa Git + +```bash +# Installa git +dnf install -y git + +# Verifica installazione +git --version +``` + +### Step 4: Clone Temporaneo Repository + +```bash +# Vai in directory temporanea +cd /tmp + +# Clone repository IDS da git.alfacom.it +# SOSTITUISCI con i tuoi dati: +git clone https://:@git.alfacom.it//ids.git + +# Esempio: +# git clone https://mario:glpat-abc123xyz@git.alfacom.it/alfacom/ids.git + +cd ids +``` + +> **IMPORTANTE**: Sostituisci: +> - `` con il tuo username git.alfacom.it +> - `` con il tuo Personal Access Token +> - `` con il proprietario del repository +> - `ids` con il nome del repository se diverso + +### Step 5: Esegui Setup AlmaLinux + +```bash +# Rendi eseguibile lo script +chmod +x deployment/setup_almalinux.sh + +# Esegui installazione base +./deployment/setup_almalinux.sh +``` + +Questo script installerΓ : +- βœ… Python 3.11 +- βœ… Node.js 20 LTS +- βœ… PostgreSQL 15 +- βœ… Utente `ids` +- βœ… Directory `/opt/ids` + +**Attendi il completamento (circa 5-10 minuti).** + +--- + +## πŸ” PARTE 2: Configurazione Repository Definitivo + +### Step 6: Clone Repository in Posizione Finale + +```bash +# Vai in directory definitiva +cd /opt/ids + +# Clone come utente ids +sudo -u ids git clone https://:@git.alfacom.it//ids.git . + +# Esempio: +# sudo -u ids git clone https://mario:glpat-abc123xyz@git.alfacom.it/alfacom/ids.git . +``` + +> **NOTA**: Il punto `.` alla fine Γ¨ importante (clona nella directory corrente) + +### Step 7: Configura git.env (Parametri Git) + +```bash +# Crea file git.env con parametri repository +sudo -u ids nano git.env +``` + +**Contenuto del file `git.env`:** + +```bash +# Credenziali Git per git.alfacom.it +GITLAB_USER=mario # ← Il tuo username +GITLAB_TOKEN=glpat-abc123xyz # ← Il tuo token +GITLAB_REPO=https://git.alfacom.it/alfacom/ids.git # ← URL repository +GITLAB_BRANCH=main # ← Branch principale +``` + +> **Come ottenere il token:** +> 1. Vai su git.alfacom.it +> 2. Settings β†’ Access Tokens +> 3. Crea token con permessi: `api`, `read_repository`, `write_repository` + +**Salva il file:** `Ctrl+O`, `Invio`, `Ctrl+X` + +### Step 8: Configura .env (Secrets Applicazione) + +```bash +# Copia template +sudo -u ids cp .env.example .env + +# Modifica .env +sudo -u ids nano .env +``` + +**Genera password sicure:** +```bash +# Password database (copia output) +openssl rand -base64 32 + +# Session secret (copia output) +openssl rand -base64 32 +``` + +**Contenuto del file `.env`:** + +```bash +# Database PostgreSQL +PGHOST=localhost +PGPORT=5432 +PGDATABASE=ids_database +PGUSER=ids_user +PGPASSWORD= # ← openssl rand -base64 32 + +# Session Secret +SESSION_SECRET= # ← openssl rand -base64 32 + +# Python Backend URL +VITE_PYTHON_API_URL=http://localhost:8000 + +# Environment +NODE_ENV=production +``` + +**Salva il file:** `Ctrl+O`, `Invio`, `Ctrl+X` + +### Step 9: Aggiorna Password Database PostgreSQL + +```bash +# Copia la password che hai messo in .env per PGPASSWORD +# Poi esegui: + +sudo -u postgres psql -c "ALTER USER ids_user WITH PASSWORD '';" + +# Esempio: +# sudo -u postgres psql -c "ALTER USER ids_user WITH PASSWORD 'aBc123XyZ456DeF789==';" +``` + +--- + +## πŸ“¦ PARTE 3: Installazione Dipendenze + +### Step 10: Installa Dipendenze Node.js + +```bash +cd /opt/ids +sudo -u ids npm install +``` + +**Attendi il completamento (circa 3-5 minuti).** + +### Step 11: Installa Dipendenze Python + +```bash +cd /opt/ids/python_ml +sudo -u ids pip3.11 install -r requirements.txt +``` + +**Attendi il completamento (circa 2-3 minuti).** + +### Step 12: Sincronizza Schema Database + +```bash +cd /opt/ids +sudo -u ids npm run db:push +``` + +Questo crea tutte le tabelle nel database PostgreSQL. + +--- + +## πŸ“‘ PARTE 4: Configurazione Raccolta Log Router + +### Step 13: Configura Server Syslog + +```bash +cd /opt/ids/deployment +chmod +x setup_syslog_server.sh +./setup_syslog_server.sh +``` + +Questo script: +- βœ… Installa e configura rsyslog +- βœ… Apre porta 514/UDP nel firewall +- βœ… Configura logrotate per log router + +**Verifica porta aperta:** +```bash +netstat -ulnp | grep 514 +``` + +Dovresti vedere: +``` +udp 0 0 0.0.0.0:514 0.0.0.0:* 12345/rsyslogd +``` + +### Step 14: Configura Router MikroTik (TUTTI i router) + +**Connettiti ad OGNI router MikroTik** (via SSH o Winbox) e esegui: + +```mikrotik +# Configura destinazione syslog (sostituisci IP_SERVER) +/system logging action +add name=ids-server target=remote remote= remote-port=514 + +# Esempio: +# add name=ids-server target=remote remote=192.168.1.100 remote-port=514 + +# Abilita logging +/system logging +add action=ids-server topics=firewall,info +add action=ids-server topics=account,info + +# Aggiungi regole firewall per loggare (opzionale ma consigliato) +/ip firewall filter +add chain=forward action=accept log=yes log-prefix="ACCEPT: " comment="Log accepted" +add chain=forward action=drop log=yes log-prefix="DROP: " comment="Log dropped" +``` + +**Verifica log in arrivo sul server:** +```bash +# Sul server AlmaLinux +tail -f /var/log/mikrotik/raw.log +``` + +Dovresti vedere log che arrivano dai router. + +--- + +## βš™οΈ PARTE 5: Avvio Sistema + +### Step 15: Avvia Syslog Parser + +```bash +cd /opt/ids/python_ml +sudo -u ids nohup python3.11 syslog_parser.py > /var/log/ids/syslog_parser.log 2>&1 & +``` + +**Verifica funzionamento:** +```bash +tail -f /var/log/ids/syslog_parser.log +``` + +### Step 16: Configura Automazione (Crontab + Servizi) + +```bash +cd /opt/ids/deployment +chmod +x setup_crontab.sh +./setup_crontab.sh +``` + +Questo script configura: +- βœ… Backend Python FastAPI (avvio automatico) +- βœ… Frontend Node.js Express (avvio automatico) +- βœ… Training ML automatico ogni 12 ore +- βœ… Detection automatica ogni 5 minuti +- βœ… Monitoring processi (riavvio se down) +- βœ… Backup database giornaliero + +**Attendi 1-2 minuti per avvio servizi.** + +--- + +## βœ… PARTE 6: Verifica Sistema Funzionante + +### Step 17: Verifica Processi Attivi + +```bash +# Verifica tutti i processi +ps aux | grep -E 'python.*main|npm.*dev|syslog_parser' +``` + +Dovresti vedere **3 processi**: +1. `python3.11 main.py` (Backend FastAPI) +2. `npm run dev` (Frontend Node) +3. `python3.11 syslog_parser.py` (Parser log) + +### Step 18: Verifica API Backend + +```bash +# Test health endpoint +curl http://localhost:8000/health + +# Risposta attesa: +# {"status":"ok"} + +# Test stats +curl http://localhost:8000/stats +``` + +### Step 19: Verifica Frontend + +```bash +# Test frontend +curl http://localhost:5000 + +# Dovresti vedere HTML della dashboard +``` + +### Step 20: Verifica Database Popolato + +```bash +# Controlla log nel database +psql -U ids_user -d ids_database -c "SELECT COUNT(*) FROM network_logs;" + +# Mostra ultimi 5 log +psql -U ids_user -d ids_database -c "SELECT * FROM network_logs ORDER BY timestamp DESC LIMIT 5;" +``` + +### Step 21: Verifica Router Configurati + +```bash +# Lista router nel database +psql -U ids_user -d ids_database -c "SELECT * FROM routers;" +``` + +Se non ci sono router, aggiungili via **dashboard web** (vedi Step 22). + +### Step 22: Accedi alla Dashboard Web + +**Da un browser:** + +``` +http://:5000 +``` + +Esempio: `http://192.168.1.100:5000` + +Dovresti vedere la dashboard IDS con: +- Dashboard (statistiche) +- Detections (rilevamenti) +- Routers (gestione router) +- Whitelist + +**Aggiungi i tuoi router:** +1. Vai su "Routers" +2. Clicca "Aggiungi Router" +3. Inserisci: + - Nome: `Router 1` + - IP: `192.168.1.1` (IP del router) + - Username: `admin` + - Password: `password_router` + - Porta API: `443` + - Enabled: βœ… + +--- + +## 🎯 PARTE 7: Primo Training ML + +### Step 23: Attendi Raccolta Log (24 ore) + +Per un training efficace, hai bisogno di **almeno 10.000 log** (circa 24 ore di traffico). + +**Monitora raccolta log:** +```bash +# Ogni ora controlla quanti log hai +psql -U ids_user -d ids_database -c "SELECT COUNT(*) FROM network_logs;" +``` + +### Step 24: Esegui Primo Training + +Quando hai almeno 10.000 log: + +```bash +curl -X POST http://localhost:8000/train \ + -H "Content-Type: application/json" \ + -d '{"max_records": 10000, "hours_back": 24, "contamination": 0.01}' +``` + +**Monitora training:** +```bash +tail -f /var/log/ids/training.log +``` + +Il training dovrebbe completarsi in ~10 secondi. + +### Step 25: Abilita Detection Automatica + +La detection Γ¨ **giΓ  configurata** in crontab (ogni 5 minuti). + +**Test manuale detection:** +```bash +curl -X POST http://localhost:8000/detect \ + -H "Content-Type: application/json" \ + -d '{"max_records": 5000, "auto_block": true, "risk_threshold": 75}' +``` + +**Monitora detection:** +```bash +tail -f /var/log/ids/detect.log +``` + +--- + +## πŸ”„ AGGIORNAMENTI FUTURI + +### Aggiornamento da Git + +Quando ci sono aggiornamenti su git.alfacom.it: + +```bash +cd /opt/ids +sudo -u ids ./deployment/update_from_git.sh +``` + +Questo script: +1. βœ… Backup configurazione locale (.env) +2. βœ… `git pull` da git.alfacom.it +3. βœ… Ripristina .env +4. βœ… Aggiorna dipendenze +5. βœ… Sync database +6. βœ… Restart servizi + +--- + +## πŸ“Š Comandi Utili + +### Log Sistema + +```bash +# Backend Python +tail -f /var/log/ids/backend.log + +# Frontend Node +tail -f /var/log/ids/frontend.log + +# Syslog Parser +tail -f /var/log/ids/syslog_parser.log + +# Training ML +tail -f /var/log/ids/training.log + +# Detection +tail -f /var/log/ids/detect.log + +# Log router in arrivo +tail -f /var/log/mikrotik/raw.log +``` + +### Restart Servizi + +```bash +# Restart completo +/opt/ids/deployment/restart_all.sh + +# Restart solo backend Python +/opt/ids/deployment/check_backend.sh + +# Restart solo frontend +/opt/ids/deployment/check_frontend.sh +``` + +### Database + +```bash +# Accedi a PostgreSQL +psql -U ids_user -d ids_database + +# Query utili +SELECT COUNT(*) FROM network_logs; +SELECT COUNT(*) FROM detections WHERE blocked = true; +SELECT * FROM routers; +SELECT * FROM whitelist; +``` + +### Monitoring + +```bash +# Processi attivi +ps aux | grep -E 'python|node' + +# Crontab configurato +crontab -u ids -l + +# Stato firewall +firewall-cmd --list-all + +# Spazio disco +df -h +``` + +--- + +## βœ… Checklist Completa + +- [ ] **Sistema Base** + - [ ] AlmaLinux 9 aggiornato + - [ ] Git installato + - [ ] Repository clonato in `/opt/ids` + +- [ ] **Configurazione** + - [ ] `git.env` configurato con credenziali git.alfacom.it + - [ ] `.env` configurato con password sicure + - [ ] Password PostgreSQL aggiornata + +- [ ] **Dipendenze** + - [ ] `npm install` completato + - [ ] `pip install` completato + - [ ] Schema database sincronizzato + +- [ ] **Syslog** + - [ ] rsyslog in ascolto porta 514 + - [ ] Firewall aperto porta 514/UDP + - [ ] Router MikroTik configurati + - [ ] Log arrivano in `/var/log/mikrotik/raw.log` + +- [ ] **Servizi** + - [ ] Syslog parser attivo + - [ ] Backend Python attivo (porta 8000) + - [ ] Frontend Node attivo (porta 5000) + - [ ] Crontab configurato + +- [ ] **Verifica** + - [ ] `curl http://localhost:8000/health` β†’ OK + - [ ] `curl http://localhost:5000` β†’ HTML + - [ ] Database `network_logs` si popola + - [ ] Dashboard accessibile da browser + +- [ ] **Training** + - [ ] Raccolti almeno 10.000 log + - [ ] Primo training eseguito con successo + - [ ] Detection automatica funzionante + +--- + +## πŸ› Troubleshooting + +### Log non arrivano dai router + +```bash +# Verifica rsyslog +systemctl status rsyslog + +# Verifica porta aperta +netstat -ulnp | grep 514 + +# Verifica firewall +firewall-cmd --list-all + +# Test da router MikroTik +# Sul router: /tool fetch url="http://:514" mode=udp +``` + +### Database non si popola + +```bash +# Verifica syslog_parser +ps aux | grep syslog_parser +tail -f /var/log/ids/syslog_parser.log + +# Riavvia parser +pkill -f syslog_parser +cd /opt/ids/python_ml +sudo -u ids nohup python3.11 syslog_parser.py > /var/log/ids/syslog_parser.log 2>&1 & +``` + +### Backend non risponde + +```bash +# Verifica processo +ps aux | grep "python.*main" +tail -f /var/log/ids/backend.log + +# Riavvia backend +/opt/ids/deployment/check_backend.sh +``` + +### Frontend non carica + +```bash +# Verifica processo +ps aux | grep "npm.*dev" +tail -f /var/log/ids/frontend.log + +# Riavvia frontend +/opt/ids/deployment/check_frontend.sh +``` + +--- + +## πŸ“ž Supporto + +Per problemi: +1. Controlla log in `/var/log/ids/` +2. Verifica `ps aux` per processi attivi +3. Controlla firewall `firewall-cmd --list-all` +4. Controlla database `psql -U ids_user -d ids_database` + +--- + +**Sistema IDS installato e funzionante! πŸ›‘οΈ** + +**Prossimi passi:** +1. Monitora raccolta log per 24h +2. Esegui primo training +3. Verifica detection automatica +4. Aggiungi IP fidati a whitelist se necessario diff --git a/git.env.example b/git.env.example new file mode 100644 index 0000000..8a370e6 --- /dev/null +++ b/git.env.example @@ -0,0 +1,26 @@ +# ============================================================================= +# GIT CONFIGURATION per git.alfacom.it +# ============================================================================= +# Questo file contiene le credenziali per accesso a git.alfacom.it +# Usato da deploy-to-gitlab.sh per push automatici +# +# IMPORTANTE: +# - Rinomina questo file in "git.env" (rimuovi .example) +# - NON committare git.env su repository (Γ¨ in .gitignore) +# - Genera token su git.alfacom.it β†’ Settings β†’ Access Tokens +# ============================================================================= + +# Username git.alfacom.it +GITLAB_USER=your-username + +# Personal Access Token +# Ottieni su: https://git.alfacom.it/-/profile/personal_access_tokens +# Permessi richiesti: api, read_repository, write_repository +GITLAB_TOKEN=your-personal-access-token + +# URL completo repository +# Formato: https://git.alfacom.it/owner/repository.git +GITLAB_REPO=https://git.alfacom.it/owner/ids.git + +# Branch principale (default: main) +GITLAB_BRANCH=main