ids.alfacom.it/deployment/INSTALLAZIONE_STEP_BY_STEP.md
marco370 f356181ada 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
2025-11-17 15:19:13 +00:00

644 lines
13 KiB
Markdown

# 🚀 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@<IP_TUO_SERVER>
# 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://<USERNAME>:<TOKEN>@git.alfacom.it/<OWNER>/ids.git
# Esempio:
# git clone https://mario:glpat-abc123xyz@git.alfacom.it/alfacom/ids.git
cd ids
```
> **IMPORTANTE**: Sostituisci:
> - `<USERNAME>` con il tuo username git.alfacom.it
> - `<TOKEN>` con il tuo Personal Access Token
> - `<OWNER>` 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://<USERNAME>:<TOKEN>@git.alfacom.it/<OWNER>/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=<INCOLLA_PASSWORD_GENERATA_1> # ← openssl rand -base64 32
# Session Secret
SESSION_SECRET=<INCOLLA_PASSWORD_GENERATA_2> # ← 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 '<LA_PASSWORD_DA_.ENV>';"
# 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=<IP_SERVER_ALMALINUX> 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://<IP_SERVER>: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://<IP_SERVER>: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