ids.alfacom.it/MIKROTIK_API_FIX.md
marco370 5c74eca030 Update MikroTik API connection to use correct REST API port
Update MIKROTIK_API_FIX.md to reflect the correction of the MikroTik API connection from the binary API port (8728) to the REST API port (80), ensuring proper HTTP communication for IP blocking functionality.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 7a657272-55ba-4a79-9a2e-f1ed9bc7a528
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Event-Id: 71f707e1-8089-4fe1-953d-aca8b360c12d
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/449cf7c4-c97a-45ae-8234-e5c5b8d6a84f/7a657272-55ba-4a79-9a2e-f1ed9bc7a528/U7LNEhO
2025-11-25 18:13:31 +00:00

312 lines
7.4 KiB
Markdown
Raw Permalink 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.

# Fix Connessione MikroTik API
## 🐛 PROBLEMA RISOLTO
**Errore**: Timeout connessione API MikroTik - router non rispondeva a richieste HTTP.
**Causa Root**: Confusione tra **API Binary** (porta 8728) e **API REST** (porta 80/443).
## 🔍 API MikroTik: Binary vs REST
MikroTik RouterOS ha **DUE tipi di API completamente diversi**:
| Tipo | Porta | Protocollo | RouterOS | Compatibilità |
|------|-------|------------|----------|---------------|
| **Binary API** | 8728 | Proprietario RouterOS | Tutte | ❌ Non HTTP (libreria `routeros-api`) |
| **REST API** | 80/443 | HTTP/HTTPS standard | **>= 7.1** | ✅ HTTP con `httpx` |
**IDS usa REST API** (httpx + HTTP), quindi:
-**Porta 80** (HTTP) - **CONSIGLIATA**
-**Porta 443** (HTTPS) - Se necessario SSL
-**Porta 8728** - API Binary, NON REST (timeout)
-**Porta 8729** - API Binary SSL, NON REST (timeout)
## ✅ SOLUZIONE
### 1⃣ Verifica RouterOS Versione
```bash
# Sul router MikroTik (via Winbox/SSH)
/system resource print
```
**Se RouterOS >= 7.1** → Usa **REST API** (porta 80/443)
**Se RouterOS < 7.1** → REST API non esiste, usa API Binary
### 2⃣ Configurazione Porta Corretta
**Per RouterOS 7.14.2 (Alfabit):**
```sql
-- Database: Usa porta 80 (REST API HTTP)
UPDATE routers SET api_port = 80 WHERE name = 'Alfabit';
```
**Porte disponibili**:
- **80** → REST API HTTP (✅ CONSIGLIATA)
- **443** → REST API HTTPS (se SSL richiesto)
- ~~8728~~ → API Binary (non compatibile)
- ~~8729~~ → API Binary SSL (non compatibile)
### 3⃣ Test Manuale
```bash
# Test connessione porta 80
curl http://185.203.24.2:80/rest/system/identity \
-u admin:password \
--max-time 5
# Output atteso:
# {"name":"AlfaBit"}
```
---
## 📋 VERIFICA CONFIGURAZIONE ROUTER
### 1⃣ Controlla Database
```sql
-- Su AlmaLinux
psql $DATABASE_URL -c "SELECT name, ip_address, api_port, username, enabled FROM routers WHERE enabled = true;"
```
**Output Atteso**:
```
name | ip_address | api_port | username | enabled
--------------+---------------+----------+----------+---------
Alfabit | 185.203.24.2 | 80 | admin | t
```
**Verifica**:
-`api_port` = **80** (REST API HTTP)
-`enabled` = **true**
-`username` e `password` corretti
**Se porta errata**:
```sql
-- Cambia porta da 8728 a 80
UPDATE routers SET api_port = 80 WHERE ip_address = '185.203.24.2';
```
### 2⃣ Testa Connessione Python
```bash
# Su AlmaLinux
cd /opt/ids/python_ml
source venv/bin/activate
# Test connessione automatico (usa dati dal database)
python3 test_mikrotik_connection.py
```
**Output atteso**:
```
✅ Connessione OK!
✅ Trovati X IP in lista 'ddos_blocked'
✅ IP bloccato con successo!
✅ IP sbloccato con successo!
```
---
## 🚀 DEPLOYMENT SU ALMALINUX
### Workflow Completo
#### 1⃣ **Su Replit** (GIÀ FATTO ✅)
- File `python_ml/mikrotik_manager.py` modificato
- Fix già committato su Replit
#### 2⃣ **Locale - Push GitLab**
```bash
# Dalla tua macchina locale (NON su Replit - è bloccato)
./push-gitlab.sh
```
Input richiesti:
```
Commit message: Fix MikroTik API - porta non usata in base_url
```
#### 3⃣ **Su AlmaLinux - Pull & Deploy**
```bash
# SSH su ids.alfacom.it
ssh root@ids.alfacom.it
# Pull ultimi cambiamenti
cd /opt/ids
./update_from_git.sh
# Riavvia ML Backend per applicare fix
sudo systemctl restart ids-ml-backend
# Verifica servizio attivo
systemctl status ids-ml-backend
# Verifica API risponde
curl http://localhost:8000/health
```
#### 4⃣ **Test Blocco IP**
```bash
# Dalla dashboard web: https://ids.alfacom.it/routers
# 1. Verifica router configurati
# 2. Clicca "Test Connessione" su router 185.203.24.2
# 3. Dovrebbe mostrare ✅ "Connessione OK"
# Dalla dashboard detections:
# 1. Seleziona detection con score >= 80
# 2. Clicca "Blocca IP"
# 3. Verifica blocco su router
```
---
## 🔧 TROUBLESHOOTING
### Connessione Ancora Fallisce?
#### A. Verifica Servizio WWW su Router
**REST API usa servizio `www` (porta 80) o `www-ssl` (porta 443)**:
```bash
# Sul router MikroTik (via Winbox/SSH)
/ip service print
# Verifica che www sia enabled:
# 0 www 80 * ← REST API HTTP
# 1 www-ssl 443 * ← REST API HTTPS
```
**Fix su MikroTik**:
```bash
# Abilita servizio www per REST API
/ip service enable www
/ip service set www port=80 address=0.0.0.0/0
# O con SSL (porta 443)
/ip service enable www-ssl
/ip service set www-ssl port=443
```
**NOTA**: `api` (porta 8728) è **API Binary**, NON REST!
#### B. Verifica Firewall AlmaLinux
```bash
# Su AlmaLinux - consenti traffico verso router
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" destination address="185.203.24.2" port protocol="tcp" port="8728" accept'
sudo firewall-cmd --reload
```
#### C. Test Connessione Raw
```bash
# Test TCP connessione porta 80
telnet 185.203.24.2 80
# Test REST API con curl
curl -v http://185.203.24.2:80/rest/system/identity \
-u admin:password \
--max-time 5
# Output atteso:
# {"name":"AlfaBit"}
```
**Se timeout**: Servizio `www` non abilitato sul router
#### D. Credenziali Errate?
```sql
-- Verifica credenziali nel database
psql $DATABASE_URL -c "SELECT name, ip_address, username FROM routers WHERE ip_address = '185.203.24.2';"
-- Se password errata, aggiorna:
-- UPDATE routers SET password = 'nuova_password' WHERE ip_address = '185.203.24.2';
```
---
## ✅ VERIFICA FINALE
Dopo il deployment, verifica che:
1. **ML Backend attivo**:
```bash
systemctl status ids-ml-backend # must be "active (running)"
```
2. **API risponde**:
```bash
curl http://localhost:8000/health
# {"status":"healthy","database":"connected",...}
```
3. **Auto-blocking funziona**:
```bash
# Controlla log auto-blocking
journalctl -u ids-auto-block.timer -n 50
```
4. **IP bloccati su router**:
- Dashboard: https://ids.alfacom.it/detections
- Filtra: "Bloccati"
- Verifica badge verde "Bloccato" visibile
---
## 📊 CONFIGURAZIONE CORRETTA
| Parametro | Valore (RouterOS >= 7.1) | Note |
|-----------|--------------------------|------|
| **api_port** | **80** (HTTP) o **443** (HTTPS) | ✅ REST API |
| **Servizio Router** | `www` (HTTP) o `www-ssl` (HTTPS) | Abilita su MikroTik |
| **Endpoint** | `/rest/system/identity` | Test connessione |
| **Endpoint** | `/rest/ip/firewall/address-list` | Gestione blocchi |
| **Auth** | Basic (username:password base64) | Header Authorization |
| **Verify SSL** | False | Self-signed certs OK |
---
## 🎯 RIEPILOGO
### ❌ ERRATO (API Binary - Timeout)
```bash
# Porta 8728 usa protocollo BINARIO, non HTTP REST
curl http://185.203.24.2:8728/rest/...
# Timeout: protocollo incompatibile
```
### ✅ CORRETTO (API REST - Funziona)
```bash
# Porta 80 usa protocollo HTTP REST standard
curl http://185.203.24.2:80/rest/system/identity \
-u admin:password
# Output: {"name":"AlfaBit"}
```
**Database configurato**:
```sql
-- Router Alfabit configurato con porta 80
SELECT name, ip_address, api_port FROM routers;
-- Alfabit | 185.203.24.2 | 80
```
---
## 📝 CHANGELOG
**25 Novembre 2024**:
1. ✅ Identificato problema: porta 8728 = API Binary (non HTTP)
2. ✅ Verificato RouterOS 7.14.2 supporta REST API
3. ✅ Configurato router con porta 80 (REST API HTTP)
4. ✅ Test curl manuale: `{"name":"AlfaBit"}`
5. ✅ Router inserito in database con porta 80
**Test richiesto**: `python3 test_mikrotik_connection.py`
**Versione**: IDS 2.0.0 (Hybrid Detector)
**RouterOS**: 7.14.2 (stable)
**API Type**: REST (HTTP porta 80)