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
externalPort = 3001
[[ports]]
localPort = 45559
externalPort = 4200
[env]
PORT = "5000"

View File

@ -2,33 +2,63 @@
## 🐛 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)
```python
base_url=f"http://{router_ip}" # ❌ Porta non specificata!
## 🔍 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
```
Il codice si connetteva sempre a:
- `http://185.203.24.2` (porta 80 HTTP standard)
**Se RouterOS >= 7.1** → Usa **REST API** (porta 80/443)
**Se RouterOS < 7.1** REST API non esiste, usa API Binary
Invece di:
- `http://185.203.24.2:8728` (porta API REST MikroTik)
- `https://185.203.24.2:8729` (porta API-SSL REST MikroTik)
### 2⃣ Configurazione Porta Corretta
### Fix Applicato
```python
protocol = "https" if use_ssl or port == 8729 else "http"
base_url=f"{protocol}://{router_ip}:{port}" # ✅ 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';
```
Ora il codice:
1. ✅ Usa la porta configurata nel database (`api_port`)
2. ✅ Auto-rileva SSL se porta = 8729
3. ✅ Supporta certificati self-signed (`verify=False`)
4. ✅ Include porta nella URL di connessione
**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"}
```
---
@ -45,59 +75,37 @@ psql $DATABASE_URL -c "SELECT name, ip_address, api_port, username, enabled FROM
```
name | ip_address | api_port | username | enabled
--------------+---------------+----------+----------+---------
Router Main | 185.203.24.2 | 8728 | admin | t
Router Office | 10.0.1.1 | 8729 | admin | t
Alfabit | 185.203.24.2 | 80 | admin | t
```
**Verifica**:
- ✅ `api_port` = **8728** (HTTP) o **8729** (HTTPS)
- ✅ `api_port` = **80** (REST API HTTP)
- ✅ `enabled` = **true**
- ✅ `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
# Su AlmaLinux
cd /opt/ids/python_ml
source venv/bin/activate
# Test connessione (sostituisci con IP/porta reali)
python3 << 'EOF'
import asyncio
from mikrotik_manager import MikroTikManager
# Test connessione automatico (usa dati dal database)
python3 test_mikrotik_connection.py
```
async def test():
manager = MikroTikManager()
# Test router (SOSTITUISCI con dati reali dal database)
result = await manager.test_connection(
router_ip="185.203.24.2",
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
**Output atteso**:
```
✅ Connessione OK!
✅ Trovati X IP in lista 'ddos_blocked'
✅ IP bloccato con successo!
✅ IP sbloccato con successo!
```
---
@ -159,27 +167,32 @@ curl http://localhost:8000/health
### 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
# Sul router MikroTik (via winbox/SSH)
# Sul router MikroTik (via Winbox/SSH)
/ip service print
# Verifica che api o api-ssl sia enabled:
# 0 api 8728 *
# 1 api-ssl 8729 *
# Verifica che www sia enabled:
# 0 www 80 * ← REST API HTTP
# 1 www-ssl 443 * ← REST API HTTPS
```
**Fix su MikroTik**:
```
# Abilita API REST
/ip service enable api
/ip service set api port=8728
```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
/ip service enable api-ssl
/ip service set api-ssl port=8729
# 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
@ -189,15 +202,20 @@ sudo firewall-cmd --reload
#### C. Test Connessione Raw
```bash
# Test TCP connessione porta 8728
telnet 185.203.24.2 8728
# Test TCP connessione porta 80
telnet 185.203.24.2 80
# O con curl
curl -v http://185.203.24.2:8728/rest/system/identity \
# 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
@ -237,33 +255,57 @@ Dopo il deployment, verifica che:
---
## 📊 PARAMETRI API CORRETTI
## 📊 CONFIGURAZIONE CORRETTA
| Router Config | HTTP | HTTPS (SSL) |
|--------------|------|-------------|
| **api_port** | 8728 | 8729 |
| **Protocollo** | http | https |
| **Endpoint** | `/rest/ip/firewall/address-list` | `/rest/ip/firewall/address-list` |
| **Auth** | Basic (username:password) | Basic (username:password) |
| **Verify SSL** | N/A | False (self-signed certs) |
| 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
**Prima** (BUG):
```
http://185.203.24.2/rest/... ❌ Porta 80 (HTTP standard) - FALLISCE
### ❌ ERRATO (API Binary - Timeout)
```bash
# 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
**Versione ML Backend**: 2.0.0 (Hybrid Detector)
**Test richiesto**: ✅ Connessione + Blocco IP manuale
## 📝 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)