# πŸš€ 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