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
This commit is contained in:
marco370 2025-11-25 18:13:31 +00:00
parent fffc53d0a6
commit 5c74eca030
2 changed files with 138 additions and 92 deletions

View File

@ -30,6 +30,10 @@ externalPort = 3000
localPort = 45059 localPort = 45059
externalPort = 3001 externalPort = 3001
[[ports]]
localPort = 45559
externalPort = 4200
[env] [env]
PORT = "5000" PORT = "5000"

View File

@ -2,33 +2,63 @@
## 🐛 PROBLEMA RISOLTO ## 🐛 PROBLEMA RISOLTO
**Errore**: "All connection attempts failed" quando si tenta di bloccare IP sui router MikroTik. **Errore**: Timeout connessione API MikroTik - router non rispondeva a richieste HTTP.
**Causa Root**: Bug nel file `python_ml/mikrotik_manager.py` - la porta API non veniva usata nella connessione HTTP. **Causa Root**: Confusione tra **API Binary** (porta 8728) e **API REST** (porta 80/443).
### Bug Originale (Riga 36) ## 🔍 API MikroTik: Binary vs REST
```python
base_url=f"http://{router_ip}" # ❌ Porta non specificata! 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
``` ```
Il codice si connetteva sempre a: **Se RouterOS >= 7.1** → Usa **REST API** (porta 80/443)
- `http://185.203.24.2` (porta 80 HTTP standard) **Se RouterOS < 7.1** REST API non esiste, usa API Binary
Invece di: ### 2⃣ Configurazione Porta Corretta
- `http://185.203.24.2:8728` (porta API REST MikroTik)
- `https://185.203.24.2:8729` (porta API-SSL REST MikroTik)
### Fix Applicato **Per RouterOS 7.14.2 (Alfabit):**
```python
protocol = "https" if use_ssl or port == 8729 else "http" ```sql
base_url=f"{protocol}://{router_ip}:{port}" # ✅ Porta corretta! -- Database: Usa porta 80 (REST API HTTP)
UPDATE routers SET api_port = 80 WHERE name = 'Alfabit';
``` ```
Ora il codice: **Porte disponibili**:
1. ✅ Usa la porta configurata nel database (`api_port`) - **80** → REST API HTTP (✅ CONSIGLIATA)
2. ✅ Auto-rileva SSL se porta = 8729 - **443** → REST API HTTPS (se SSL richiesto)
3. ✅ Supporta certificati self-signed (`verify=False`) - ~~8728~~ → API Binary (non compatibile)
4. ✅ Include porta nella URL di connessione - ~~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"}
```
--- ---
@ -45,59 +75,37 @@ psql $DATABASE_URL -c "SELECT name, ip_address, api_port, username, enabled FROM
``` ```
name | ip_address | api_port | username | enabled name | ip_address | api_port | username | enabled
--------------+---------------+----------+----------+--------- --------------+---------------+----------+----------+---------
Router Main | 185.203.24.2 | 8728 | admin | t Alfabit | 185.203.24.2 | 80 | admin | t
Router Office | 10.0.1.1 | 8729 | admin | t
``` ```
**Verifica**: **Verifica**:
- ✅ `api_port` = **8728** (HTTP) o **8729** (HTTPS) - ✅ `api_port` = **80** (REST API HTTP)
- ✅ `enabled` = **true** - ✅ `enabled` = **true**
- ✅ `username` e `password` corretti - ✅ `username` e `password` corretti
### 2⃣ Testa Connessione Manualmente **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 ```bash
# Su AlmaLinux # Su AlmaLinux
cd /opt/ids/python_ml cd /opt/ids/python_ml
source venv/bin/activate source venv/bin/activate
# Test connessione (sostituisci con IP/porta reali) # Test connessione automatico (usa dati dal database)
python3 << 'EOF' python3 test_mikrotik_connection.py
import asyncio ```
from mikrotik_manager import MikroTikManager
async def test(): **Output atteso**:
manager = MikroTikManager() ```
✅ Connessione OK!
# Test router (SOSTITUISCI con dati reali dal database) ✅ Trovati X IP in lista 'ddos_blocked'
result = await manager.test_connection( ✅ IP bloccato con successo!
router_ip="185.203.24.2", ✅ IP sbloccato con successo!
username="admin", # Dal database
password="your_password", # Dal database
port=8728 # Dal database
)
print(f"Connessione: {'✅ OK' if result else '❌ FALLITA'}")
if result:
# Test blocco IP
print("\nTest blocco IP 1.2.3.4...")
blocked = await manager.add_address_list(
router_ip="185.203.24.2",
username="admin",
password="your_password",
ip_address="1.2.3.4",
list_name="ddos_test",
comment="Test IDS API Fix",
timeout_duration="5m",
port=8728
)
print(f"Blocco: {'✅ OK' if blocked else '❌ FALLITO'}")
await manager.close_all()
asyncio.run(test())
EOF
``` ```
--- ---
@ -159,27 +167,32 @@ curl http://localhost:8000/health
### Connessione Ancora Fallisce? ### Connessione Ancora Fallisce?
#### A. Verifica Firewall su Router #### A. Verifica Servizio WWW su Router
**REST API usa servizio `www` (porta 80) o `www-ssl` (porta 443)**:
```bash ```bash
# Sul router MikroTik (via winbox/SSH) # Sul router MikroTik (via Winbox/SSH)
/ip service print /ip service print
# Verifica che api o api-ssl sia enabled: # Verifica che www sia enabled:
# 0 api 8728 * # 0 www 80 * ← REST API HTTP
# 1 api-ssl 8729 * # 1 www-ssl 443 * ← REST API HTTPS
``` ```
**Fix su MikroTik**: **Fix su MikroTik**:
``` ```bash
# Abilita API REST # Abilita servizio www per REST API
/ip service enable api /ip service enable www
/ip service set api port=8728 /ip service set www port=80 address=0.0.0.0/0
# O con SSL # O con SSL (porta 443)
/ip service enable api-ssl /ip service enable www-ssl
/ip service set api-ssl port=8729 /ip service set www-ssl port=443
``` ```
**NOTA**: `api` (porta 8728) è **API Binary**, NON REST!
#### B. Verifica Firewall AlmaLinux #### B. Verifica Firewall AlmaLinux
```bash ```bash
# Su AlmaLinux - consenti traffico verso router # Su AlmaLinux - consenti traffico verso router
@ -189,15 +202,20 @@ sudo firewall-cmd --reload
#### C. Test Connessione Raw #### C. Test Connessione Raw
```bash ```bash
# Test TCP connessione porta 8728 # Test TCP connessione porta 80
telnet 185.203.24.2 8728 telnet 185.203.24.2 80
# O con curl # Test REST API con curl
curl -v http://185.203.24.2:8728/rest/system/identity \ curl -v http://185.203.24.2:80/rest/system/identity \
-u admin:password \ -u admin:password \
--max-time 5 --max-time 5
# Output atteso:
# {"name":"AlfaBit"}
``` ```
**Se timeout**: Servizio `www` non abilitato sul router
#### D. Credenziali Errate? #### D. Credenziali Errate?
```sql ```sql
-- Verifica credenziali nel database -- Verifica credenziali nel database
@ -237,33 +255,57 @@ Dopo il deployment, verifica che:
--- ---
## 📊 PARAMETRI API CORRETTI ## 📊 CONFIGURAZIONE CORRETTA
| Router Config | HTTP | HTTPS (SSL) | | Parametro | Valore (RouterOS >= 7.1) | Note |
|--------------|------|-------------| |-----------|--------------------------|------|
| **api_port** | 8728 | 8729 | | **api_port** | **80** (HTTP) o **443** (HTTPS) | ✅ REST API |
| **Protocollo** | http | https | | **Servizio Router** | `www` (HTTP) o `www-ssl` (HTTPS) | Abilita su MikroTik |
| **Endpoint** | `/rest/ip/firewall/address-list` | `/rest/ip/firewall/address-list` | | **Endpoint** | `/rest/system/identity` | Test connessione |
| **Auth** | Basic (username:password) | Basic (username:password) | | **Endpoint** | `/rest/ip/firewall/address-list` | Gestione blocchi |
| **Verify SSL** | N/A | False (self-signed certs) | | **Auth** | Basic (username:password base64) | Header Authorization |
| **Verify SSL** | False | Self-signed certs OK |
--- ---
## 🎯 RIEPILOGO ## 🎯 RIEPILOGO
**Prima** (BUG): ### ❌ ERRATO (API Binary - Timeout)
``` ```bash
http://185.203.24.2/rest/... ❌ Porta 80 (HTTP standard) - FALLISCE # Porta 8728 usa protocollo BINARIO, non HTTP REST
curl http://185.203.24.2:8728/rest/...
# Timeout: protocollo incompatibile
``` ```
**Dopo** (FIX): ### ✅ 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"}
``` ```
http://185.203.24.2:8728/rest/... ✅ Porta 8728 (API REST) - FUNZIONA
https://185.203.24.2:8729/rest/... ✅ Porta 8729 (API-SSL) - FUNZIONA **Database configurato**:
```sql
-- Router Alfabit configurato con porta 80
SELECT name, ip_address, api_port FROM routers;
-- Alfabit | 185.203.24.2 | 80
``` ```
--- ---
**Fix applicato**: 25 Novembre 2024 ## 📝 CHANGELOG
**Versione ML Backend**: 2.0.0 (Hybrid Detector)
**Test richiesto**: ✅ Connessione + Blocco IP manuale **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)